package com.ja.openchat.ui.chat;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.BarUtils;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videoplayer.player.VideoView;
import com.github.chrisbanes.photoview.PhotoView;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.views.FingerViewGroup;
import com.zy.openchat.core.model.circle.MediaInfo;
import com.zy.openchat.util.glide.GlideApp;

import java.util.ArrayList;
import java.util.List;

/**
 * @author imndx
 */
public class PreviewLocalMediaActivity extends JaBaseActivity {
    private SparseArray<View> views;
    private View currentVideoView;
    private ViewPager viewPager;
    private MMPagerAdapter adapter;

    private static int currentPosition = -1;
    private static List<MediaInfo> entries;
    private boolean pendingPreviewInitialMedia;

    private class MMPagerAdapter extends PagerAdapter {
        private List<MediaInfo> entries;

        public MMPagerAdapter(List<MediaInfo> entries) {
            this.entries = entries;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            View view;
            MediaInfo entry = entries.get(position);
            if (!entry.isVideo()) {
                view = LayoutInflater.from(PreviewLocalMediaActivity.this).inflate(R.layout.preview_photo, null);
            } else {
                view = LayoutInflater.from(PreviewLocalMediaActivity.this).inflate(R.layout.preview_video, null);
            }
            view.setTag(position);
            container.addView(view);
            views.put(position % 3, view);
            if (pendingPreviewInitialMedia) {
                preview(view, entry);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
            // do nothing ?
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return entries == null ? 0 : entries.size();
        }

        public MediaInfo getEntry(int position) {
            return entries.get(position);
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }
    }

    final ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // TODO 可以在此控制透明度
        }

        @Override
        public void onPageSelected(int position) {
            View view = views.get(position % 3);
            if (view == null) {
                // pending layout
                return;
            }
            if (currentVideoView != null) {
                resetVideoView(currentVideoView);
                currentVideoView = null;
            }
            setCurrentTitle(position);
            MediaInfo entry = adapter.getEntry(position);
            preview(view, entry);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private boolean isImageType(MediaInfo message){
        if(message==null){
            return false;
        }
        if(!message.isVideo()){
            return true;
        }
        return false;
    }

    private void preview(View view, MediaInfo message) {
        if (isImageType(message)) {
            previewImage(view, message);
        } else {
            previewVideo(view, message);
        }
    }

    private void resetVideoView(View view) {
        PhotoView photoView = view.findViewById(R.id.photoView);
        VideoView videoView = view.findViewById(R.id.videoView);

        photoView.setVisibility(View.VISIBLE);
        videoView.pause();
    }

    private void previewVideo(View view, MediaInfo entry) {

        PhotoView photoView = view.findViewById(R.id.photoView);
        GlideApp.with(photoView).load(entry.getMediaPath()).into(photoView);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playVideo(view, entry.getMediaPath());
            }
        });

        if(isFirstShow){
            isFirstShow = false;
            view.post(new Runnable() {
                @Override
                public void run() {
                    if(view!=null){
                        view.performClick();
                    }
                }
            });
        }

    }

    private boolean isFirstShow = true;

    private void playVideo(View view, String videoUrl) {
        VideoView videoView = view.findViewById(R.id.videoView);

        PhotoView photoView = view.findViewById(R.id.photoView);
        photoView.setVisibility(View.GONE);
        currentVideoView = view;

        videoView.setVisibility(View.VISIBLE);
        videoView.setUrl(videoUrl); //设置视频地址
        StandardVideoController controller = new StandardVideoController(this);
        controller.addDefaultControlComponent("预览", false);
        videoView.setVideoController(controller); //设置控制器
        videoView.start(); //开始播放，不调用则不自动播放

    }


    private void previewImage(View view, MediaInfo entry) {
        PhotoView photoView = view.findViewById(R.id.photoView);
        GlideApp.with(PreviewLocalMediaActivity.this).load(entry.getMediaPath())
                .into(photoView);

    }

    private TextView tv_bar_title;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_mm_preview;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initView() {
        super.initView();
        views = new SparseArray<>(3);
        viewPager = findViewById(R.id.viewPager);
        adapter = new MMPagerAdapter(entries);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(1);
        viewPager.addOnPageChangeListener(pageChangeListener);
        tv_bar_title = findViewById(R.id.tv_bar_title);

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setBackgroundResource(R.drawable.transparent_shape);
        ((ViewGroup.MarginLayoutParams)toolbar.getLayoutParams()).topMargin = ImmersionBar.getStatusBarHeight(this);
        tv_bar_title.setTextColor(ContextCompat.getColor(this,R.color.white));
        AppCompatImageView iv_bar_right = findViewById(R.id.iv_bar_right);
        AppCompatImageView iv_bar_back = findViewById(R.id.iv_bar_back);
        iv_bar_back.setImageResource(R.mipmap.com_nav_ic_back_white_normal);
        iv_bar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (currentPosition == 0) {
            viewPager.post(() -> {
                pageChangeListener.onPageSelected(0);
            });
            setCurrentTitle(0);
        } else {
            viewPager.setCurrentItem(currentPosition);
            pendingPreviewInitialMedia = true;
            setCurrentTitle(currentPosition);
        }
        FingerViewGroup adFingerViewGroup = findViewById(R.id.ad_finger_vg);
        adFingerViewGroup.setOnAlphaChangeListener(new FingerViewGroup.onAlphaChangedListener() {
            @Override
            public void onAlphaChanged(float alpha) {
            }

            @Override
            public void onTranslationYChanged(float translationY) {
            }

            @Override
            public void onFinishAction() {
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        });

    }

    private void setCurrentTitle(int currentIndex){
        if(entries!=null&&entries.size()>currentIndex&&isImageType(entries.get(currentIndex))){
            tv_bar_title.setText(String.format("%d/%d",currentIndex+1,entries.size()));
        }else{
            tv_bar_title.setText("");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
            ((VideoView)currentVideoView.findViewById(R.id.videoView)).pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
            ((VideoView)currentVideoView.findViewById(R.id.videoView)).resume();
        }

    }

    @Override
    public void setStatusBar() {
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

//    @Override
//    public void onBackPressed() {
//        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
//            if (!((VideoView)currentVideoView.findViewById(R.id.videoView)).onBackPressed()) {
//                super.onBackPressed();
//            }
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        entries = null;
        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
            ((VideoView)currentVideoView.findViewById(R.id.videoView)).release();
        }
    }

    public static void previewMedia(Context context, List<MediaInfo> entries, int current) {
        if (entries == null || entries.isEmpty()) {
            Log.w(PreviewLocalMediaActivity.class.getSimpleName(), "message is null or empty");
            return;
        }
        PreviewLocalMediaActivity.entries = entries;
        PreviewLocalMediaActivity.currentPosition = current;
        Intent intent = new Intent(context, PreviewLocalMediaActivity.class);
        context.startActivity(intent);
    }

    public static void previewImage(Context context, MediaInfo imageMessageContent) {
        List<MediaInfo> entries = new ArrayList<>();
        entries.add(imageMessageContent);
        previewMedia(context, entries, 0);
    }


    public static void previewVideo(Context context, MediaInfo videoMessageContent) {
        List<MediaInfo> entries = new ArrayList<>();

        entries.add(videoMessageContent);
        previewMedia(context, entries, 0);
    }

}
